import React, { useState, useEffect } from 'react';
// import styles from '../styles/Reference.module.css';
import '../styles/Reference.module.css';

import { List, Typography, Modal, Tooltip, Collapse, Drawer, Card, message } from 'antd';
import { FileOutlined } from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';

import { Quote } from '../tools/constants';
import useWindowWidth from '@/hooks/event/use-window-width';
import datasetService from '@/api/services/datasetService';
import '../styles/reference.css';
import FilePreviewDrawer from '@/pages/components/fileviewer/FilePreviewDrawer';

import { useDatasetPermit } from '@/store/configStore';

const { Text } = Typography;
const { Panel } = Collapse;

const Reference: React.FC<{
  files: Quote[];
  onChange: (isExpanded: boolean) => void;
  defaultCollectionId?: string;
  initCollectionId?: () => void;
}> = ({ files, onChange, defaultCollectionId, initCollectionId }) => {
  const [groupedFiles, setGroupedFiles] = useState<{ [key: string]: Quote[] }>({});
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [referenceDetail, setReferenceDetail] = useState<Quote[]>([]);
  const [isPanelExpanded, setIsPanelExpanded] = useState(false);
  const { isPc } = useWindowWidth();
  const [isPreview, setIsPreview] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [previewFileName, setPreviewFileName] = useState<string>('');
  const [loading, setLoading] = useState(false);

  // const datasetPermit = useDatasetPermit();

  useEffect(() => {
    const grouped = files.reduce((acc, file) => {
      const key = file?.sourceName;
      if (!acc[key]) {
        acc[key] = [];
      }
      const scoreItem = file?.score.find((item) => item.type === 'fullText');
      if (scoreItem) {
        file.s = scoreItem.value;
      }
      acc[key].push(file);
      return acc;
    }, {} as { [key: string]: Quote[] });

    for (const sourceName in grouped) {
      grouped[sourceName].sort((a, b) => {
        // const scoreA = a.score.find(s => s.type === 'fullText')?.value || 0;
        // const scoreB = b.score.find(s => s.type === 'fullText')?.value || 0;
        // return scoreB - scoreA;
        return b.s - a.s;
      });
    }

    setGroupedFiles(grouped);
  }, [files]);

  useEffect(() => {
    if (defaultCollectionId) {
      const source = files.find((file) => file.collectionId === defaultCollectionId);
      if (source) {
        showDrawer(source);
      }
    }
  }, [defaultCollectionId, files]);

  const referenceStyle: React.CSSProperties = {
    borderRadius: '12px',
    backgroundColor: '#00134D0A !important',
    // backgroundColor: '#F5F6F8 !important',
    // backgroundColor: 'transparent !important',
  };

  const uniqueFiles = Array.from(new Set(files.map((file) => file?.sourceName)))
    .map((sourceName) => files.find((file) => file?.sourceName === sourceName))
    .filter(Boolean) as Quote[];

  // const uniqueFiles = Array.from(new Set(files.map((file) => file?.sourceName)))
  //   .map((sourceName) => files.find((file) => file?.sourceName === sourceName))
  //   .filter(Boolean)
  //   .filter((file) => file?.sourceId == 'link' || (file?.sourceId != 'link' && file?.datasetId && datasetPermit.includes(file?.datasetId))) as Quote[];

  const processText = (inputText: string) => {
    // 使用正则表达式去除 HTML 标签
    const textWithoutHtml = inputText
      .replace(/<[^>]*>/g, '\n')
      .replace(' ', '\n')
      .replace(/[^a-zA-Z\u4e00-\u9fa5\s]/g, '\n');
    // 按行分割文本，去除空行，然后用竖线连接
    const lines = textWithoutHtml
      .split('\n')
      .map((line) => line.trim()) // 去掉每行的首尾空格
      .filter((line) => line !== ''); // 去除空行
    const result = lines.join('|');
    return result;
  };

  // 根据文件名后缀判断是否为视频文件
  const isVideoFile = (fileName: string) => {
    if (!fileName) return false;
    const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.mpeg', '.mpg', '.3gp', '.rmvb', '.rm'];
    const lowerFileName = fileName.toLowerCase();
    return videoExtensions.some(ext => lowerFileName.endsWith(ext));
  };

  // 根据文件名后缀判断是否为图片文件
  const isImageFile = (fileName: string) => {
    if (!fileName) return false;
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.tiff', '.tif'];
    const lowerFileName = fileName.toLowerCase();
    return imageExtensions.some(ext => lowerFileName.endsWith(ext));
  };

  const showDrawer = async (source: Quote) => {
    if (source?.sourceId == 'link') {
      source?.collectionId?.startsWith('http') && window.open(source?.collectionId);
      return;
    }
    setReferenceDetail(groupedFiles[source.sourceName] || []);
    try {
      const res = await datasetService.collectionPreviewInfo({
        collection_id: source.collectionId,
      });
      if (res && res.url) {
        if (!res.preview) {
          message.error('文件不支持预览！');
          return;
        }
        setLoading(true);
        var keyword = res.show_keyword ? processText(source.q) : '';
        if (keyword.length > 200) {
          keyword = keyword.substring(0, 200);
        }
        if (res.type == 'file') {
          setPreviewFileName(res.filename);
          if (res.filename.endsWith('.md')) {
            setPreviewUrl(res.file_url);
          } else if (isVideoFile(res.filename) || isImageFile(res.filename)) {
            setLoading(false);
            if (source?.metadata?.start != undefined && source?.metadata?.end != undefined) {
              // 支持整数和小数字符串
              const startNum = Number(source?.metadata?.start);
              const endNum = Number(source?.metadata?.end);
              if (isNaN(startNum) || isNaN(endNum)) {
                setPreviewUrl(res.url);
              } else {
                setPreviewUrl(res.url + `?start=${Math.floor(startNum)}&end=${Math.ceil(endNum)}`);
              }
            } else {
              setPreviewUrl(res.url);
            }
          } else {
            setPreviewUrl(res.url + `&officePreviewType=pdf&keyword=${keyword}`);
          }
          setIsPreview(true);
        } else {
          window.open(res.url);
        }
      }
    } catch (error) {
      console.log(error);
      message.error(error.message);
    }
  };

  const onCloseDrawer = () => {
    setIsDrawerOpen(false);
  };

  const onClosePreview = () => {
    setIsPreview(false);
    initCollectionId && initCollectionId();
  };

  const handleCollapseChange = (key: string | string[]) => {
    const isExpanded = key.length > 0;
    setIsPanelExpanded(isExpanded);
    onChange(isExpanded);
  };

  return (
    <>
      {uniqueFiles.length > 0 && (
        // <div style={referenceStyle} className="custom-reference">
        <Collapse
          // className="custom-collapse"
          accordion onChange={handleCollapseChange}
          style={{ border: 'none', borderRadius: '12px', backgroundColor: '#00134D0A' }}
        >
          <Panel
            header={
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                {/* <SvgIcon icon="ic_rj_reference" size="10" /> */}
                <span
                  // style={{
                  //   color: '#8E93A4',
                  //   paddingLeft: '10px',
                  //   paddingRight: '10px',
                  //   fontSize: '14px',
                  // }}
                  className='text-[14px] text-text-4'
                >{`引用 ${uniqueFiles.length} 份资料回答`}</span>
                {isPanelExpanded ? (
                  <SvgIcon icon="ai-chat-down" size="12" />
                ) : (
                  <SvgIcon icon="ai-chat-right" size="12" />
                )}
              </div>
            }
            key="1"
            className="custom-panel"
          >
            <div
              style={{
                flexWrap: 'wrap',
                gap: '16px',
                margin: '0 0 0 5px',
                padding: '0 0 0 5px',
                borderLeft: '2px solid #E5E6EB',
              }}
            >
              {uniqueFiles.map((item) => (
                <div
                  key={item.id}
                  onClick={() => showDrawer(item)}
                  style={{
                    borderRadius: '5px',
                    padding: '2px 5px',
                    cursor: 'pointer',
                    maxWidth: '100%',
                  }}
                  className="file-name flex items-center"
                >
                  <SvgIcon icon="ai-chat-file" size="16" />
                  <span className="ellipsis pl-2">{item?.sourceName}</span>
                </div>
              ))}
            </div>
          </Panel>
        </Collapse>
        // </div>
      )}

      <Drawer
        title={referenceDetail.length > 0 ? referenceDetail[0].sourceName : ''}
        placement="right"
        onClose={onCloseDrawer}
        open={isDrawerOpen}
        zIndex={500}
        width={isPc ? '30%' : '100%'}
        closeIcon={isPc ? undefined : <SvgIcon icon="ic-back" size={24} />}
      >
        {referenceDetail.map((item, index) => (
          <Card key={index} style={{ marginBottom: '16px' }} title={`综合得分: ${item.s}`}>
            <p style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>{item.q}</p>
          </Card>
        ))}
      </Drawer>
      <FilePreviewDrawer
        loading={loading}
        setLoading={setLoading}
        open={isPreview}
        previewUrl={previewUrl}
        fileName={previewFileName}
        onClose={onClosePreview}
      />
    </>
  );
};

export default Reference;
